<template>
  <div class="song-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>歌曲管理</span>
          <el-button type="primary" @click="handleCreate">新增歌曲</el-button>
        </div>
      </template>

      <!-- Search Form -->
      <el-form :model="searchForm" inline>
        <el-form-item label="歌曲名称">
          <el-input v-model="searchForm.songName" placeholder="请输入歌曲名称" clearable />
        </el-form-item>
        <el-form-item label="歌手">
          <el-input v-model="searchForm.artistName" placeholder="请输入歌手名称" clearable />
        </el-form-item>
        <el-form-item label="专辑">
          <el-input v-model="searchForm.albumName" placeholder="请输入专辑名称" clearable />
        </el-form-item>
        <el-form-item label="音乐风格">
          <el-select v-model="searchForm.genre" placeholder="请选择音乐风格" clearable>
            <el-option label="流行" value="流行" />
            <el-option label="摇滚" value="摇滚" />
            <el-option label="古典" value="古典" />
            <el-option label="爵士" value="爵士" />
            <el-option label="电子" value="电子" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- Song Table -->
      <el-table
          :data="songList"
          v-loading="loading"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="songId" label="ID" width="80" />
        <el-table-column prop="songName" label="歌曲名称" width="180" />
        <el-table-column label="歌手" width="180">
          <template #default="{ row }">
            <div v-if="row.artist">
              {{ row.artist.artistName }} (ID: {{ row.artist.artistId }})
            </div>
            <div v-else>
              歌手ID: {{ row.artistId }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="专辑" width="180">
          <template #default="{ row }">
            <div v-if="row.album">
              {{ row.album.albumName }} (ID: {{ row.album.albumId }})
            </div>
            <div v-else>
              专辑ID: {{ row.albumId }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="封面" width="120">
          <template #default="{ row }">
            <el-image
                style="width: 80px; height: 80px"
                :src="row.coverUrl"
                :preview-src-list="[row.coverUrl]"
                fit="cover"
                hide-on-click-modal
            />
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长(秒)" width="100" />
        <el-table-column prop="genre" label="音乐风格" width="120" />
        <el-table-column prop="language" label="语言" width="100" />
        <el-table-column label="VIP歌曲" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isVip ? 'warning' : 'info'">
              {{ row.isVip ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.songId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>

      <!-- Batch Actions -->
      <div class="batch-actions" v-if="selectedSongs.length > 0">
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
        <span class="selected-count">已选择 {{ selectedSongs.length }} 项</span>
      </div>
    </el-card>

    <!-- Song Form Dialog -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
        :close-on-click-modal="false"
        @closed="resetForm"
    >
      <el-form
          ref="songFormRef"
          :model="songForm"
          :rules="songRules"
          label-width="100px"
          label-position="right"
      >
        <el-form-item label="歌曲名称" prop="songName">
          <el-input v-model="songForm.songName" placeholder="请输入歌曲名称" />
        </el-form-item>
        <el-form-item label="歌手" prop="artistId">
          <el-select
              v-model="songForm.artistId"
              filterable
              remote
              reserve-keyword
              placeholder="请搜索并选择歌手"
              :remote-method="searchArtists"
              :loading="artistLoading"
          >
            <el-option
                v-for="artist in artistOptions"
                :key="artist.artistId"
                :label="`${artist.artistName} (ID: ${artist.artistId})`"
                :value="artist.artistId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专辑" prop="albumId">
          <el-select
              v-model="songForm.albumId"
              filterable
              remote
              reserve-keyword
              placeholder="请搜索并选择专辑"
              :remote-method="searchAlbums"
              :loading="albumLoading"
          >
            <el-option
                v-for="album in albumOptions"
                :key="album.albumId"
                :label="`${album.albumName} (ID: ${album.albumId})`"
                :value="album.albumId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="封面URL" prop="coverUrl">
          <el-input v-model="songForm.coverUrl" placeholder="请输入封面URL" />
          <el-upload
              class="avatar-uploader"
              action="#"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleCoverChange"
          >
            <el-button type="primary">上传封面</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="音频文件URL" prop="fileUrl">
          <el-input v-model="songForm.fileUrl" placeholder="请输入音频文件URL" />
        </el-form-item>
        <el-form-item label="歌词文件URL" prop="lyricUrl">
          <el-input v-model="songForm.lyricUrl" placeholder="请输入歌词文件URL" />
        </el-form-item>
        <el-form-item label="时长(秒)" prop="duration">
          <el-input-number v-model="songForm.duration" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="音乐风格" prop="genre">
          <el-select v-model="songForm.genre" placeholder="请选择音乐风格">
            <el-option label="流行" value="流行" />
            <el-option label="摇滚" value="摇滚" />
            <el-option label="古典" value="古典" />
            <el-option label="爵士" value="爵士" />
            <el-option label="电子" value="电子" />
            <el-option label="民谣" value="民谣" />
            <el-option label="嘻哈" value="嘻哈" />
            <el-option label="R&B" value="R&B" />
          </el-select>
        </el-form-item>
        <el-form-item label="语言" prop="language">
          <el-input v-model="songForm.language" placeholder="请输入语言" />
        </el-form-item>
        <el-form-item label="发行日期" prop="releaseDate">
          <el-date-picker
              v-model="songForm.releaseDate"
              type="date"
              placeholder="选择发行日期"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="音频格式" prop="format">
          <el-input v-model="songForm.format" placeholder="请输入音频格式" />
        </el-form-item>
        <el-form-item label="比特率" prop="bitRate">
          <el-input-number v-model="songForm.bitRate" :min="0" :step="64" />
        </el-form-item>
        <el-form-item label="文件大小" prop="fileSize">
          <el-input-number v-model="songForm.fileSize" :min="0" :step="1024" />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-select
              v-model="songForm.tags"
              multiple
              filterable
              allow-create
              placeholder="请输入标签"
          />
        </el-form-item>
        <el-form-item label="VIP歌曲" prop="isVip">
          <el-switch
              v-model="songForm.isVip"
              active-text="是"
              inactive-text="否"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
              v-model="songForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../services/api'

// 数据状态
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增歌曲')
const songFormRef = ref(null)
const artistLoading = ref(false)
const artistOptions = ref([])
const albumLoading = ref(false)
const albumOptions = ref([])
const selectedSongs = ref([])

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  songName: '',
  artistName: '',
  albumName: '',
  genre: '',
  status: ''
})

// 歌曲表单
const songForm = reactive({
  songId: null,
  songName: '',
  artistId: null,
  albumId: null,
  coverUrl: '',
  fileUrl: '',
  lyricUrl: '',
  duration: 0,
  genre: '',
  language: '中文',
  releaseDate: '',
  format: 'MP3',
  bitRate: 320,
  fileSize: 0,
  tags: [],
  isVip: false,
  status: 1
})

// 表单验证规则
const songRules = reactive({
  songName: [
    { required: true, message: '请输入歌曲名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  artistId: [
    { required: true, message: '请选择歌手', trigger: 'change' }
  ],
  coverUrl: [
    { required: true, message: '请输入封面URL', trigger: 'blur' }
  ],
  fileUrl: [
    { required: true, message: '请输入音频文件URL', trigger: 'blur' }
  ],
  duration: [
    { required: true, message: '请输入时长', trigger: 'blur' }
  ],
  genre: [
    { required: true, message: '请选择音乐风格', trigger: 'change' }
  ]
})

// 歌曲列表数据
const songList = ref([])

// 生命周期钩子
onMounted(() => {
  fetchSongList()
})

// 获取歌曲列表
const fetchSongList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }

    const response = await api.contentManageApi.getSongManageList(params)

    if (response.code === 200) {
      // 处理后端返回的数据结构
      const data = response.data
      songList.value = data.records || data.list || []

      // 处理分页信息
      pagination.total = data.total || 0

      // 如果后端没有返回分页信息，使用records数组长度
      if (!data.total && data.records) {
        pagination.total = data.records.length
      }
    } else {
      ElMessage.error(response.message || '获取歌曲列表失败')
    }
  } catch (error) {
    console.error('获取歌曲列表出错:', error)
    ElMessage.error('获取歌曲列表出错')
  } finally {
    loading.value = false
  }
}

// 搜索歌手
const searchArtists = async (query) => {
  if (query) {
    artistLoading.value = true
    try {
      const response = await api.artistApi.searchArtists({ keyword: query, page: 1, size: 10 })
      if (response.code === 200) {
        artistOptions.value = response.data.list
      }
    } catch (error) {
      console.error('搜索歌手出错:', error)
    } finally {
      artistLoading.value = false
    }
  }
}

// 搜索专辑
const searchAlbums = async (query) => {
  if (query) {
    albumLoading.value = true
    try {
      const response = await api.albumApi.searchAlbums({ keyword: query, page: 1, size: 10 })
      if (response.code === 200) {
        albumOptions.value = response.data.list
      }
    } catch (error) {
      console.error('搜索专辑出错:', error)
    } finally {
      albumLoading.value = false
    }
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1
  fetchSongList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  fetchSongList()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  fetchSongList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedSongs.value = selection.map(item => item.songId)
}

// 打开创建对话框
const handleCreate = () => {
  dialogTitle.value = '新增歌曲'
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑歌曲'
  Object.keys(songForm).forEach(key => {
    if (key === 'artist') {
      songForm.artistId = row.artist.artistId
      artistOptions.value = [row.artist]
    } else if (key === 'album') {
      songForm.albumId = row.album.albumId
      albumOptions.value = [row.album]
    } else if (row[key] !== undefined) {
      songForm[key] = row[key]
    }
  })

  // 处理tags数组
  if (row.tags && typeof row.tags === 'string') {
    songForm.tags = row.tags.split(',')
  } else if (Array.isArray(row.tags)) {
    songForm.tags = [...row.tags]
  } else {
    songForm.tags = []
  }

  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    await songFormRef.value.validate()

    const formData = { ...songForm }
    // 移除songId如果是新增
    if (!formData.songId) {
      delete formData.songId
    }

    // 处理tags数组
    if (formData.tags && Array.isArray(formData.tags)) {
      formData.tags = formData.tags.join(',')
    }

    let response
    if (formData.songId) {
      // 更新歌曲
      response = await api.contentManageApi.updateSong(formData.songId, formData)
    } else {
      // 创建歌曲
      response = await api.contentManageApi.createSong(formData)
    }

    if (response.code === 200) {
      ElMessage.success(formData.songId ? '更新歌曲成功' : '创建歌曲成功')
      dialogVisible.value = false
      fetchSongList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('表单提交出错:', error)
    if (error instanceof Error) {
      ElMessage.error(error.message || '表单验证失败')
    }
  }
}

// 删除歌曲
const handleDelete = (songId) => {
  ElMessageBox.confirm('确认删除该歌曲吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await api.contentManageApi.deleteSong(songId)
      if (response.code === 200) {
        ElMessage.success('删除歌曲成功')
        fetchSongList()
      } else {
        ElMessage.error(response.message || '删除歌曲失败')
      }
    } catch (error) {
      console.error('删除歌曲出错:', error)
      ElMessage.error('删除歌曲出错')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 批量删除
const batchDelete = () => {
  if (selectedSongs.value.length === 0) {
    ElMessage.warning('请至少选择一项')
    return
  }

  ElMessageBox.confirm(`确认删除选中的 ${selectedSongs.value.length} 首歌曲吗?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await api.contentManageApi.batchDeleteSongs({ songIds: selectedSongs.value })
      if (response.code === 200) {
        ElMessage.success('批量删除成功')
        selectedSongs.value = []
        fetchSongList()
      } else {
        ElMessage.error(response.message || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除出错:', error)
      ElMessage.error('批量删除出错')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 重置表单
const resetForm = () => {
  songFormRef.value?.resetFields()
  Object.keys(songForm).forEach(key => {
    if (key === 'status') {
      songForm[key] = 1
    } else if (key === 'language') {
      songForm[key] = '中文'
    } else if (key === 'format') {
      songForm[key] = 'MP3'
    } else if (key === 'bitRate') {
      songForm[key] = 320
    } else if (key === 'fileSize') {
      songForm[key] = 0
    } else if (key === 'tags') {
      songForm[key] = []
    } else if (key === 'isVip') {
      songForm[key] = false
    } else {
      songForm[key] = ''
    }
  })
  songForm.songId = null
  songForm.duration = 0
  artistOptions.value = []
  albumOptions.value = []
}

// 封面文件变化
const handleCoverChange = (file) => {
  // 这里应该有实际上传逻辑，暂时只是模拟
  const reader = new FileReader()
  reader.onload = () => {
    songForm.coverUrl = reader.result
  }
  reader.readAsDataURL(file.raw)
}
</script>

<style scoped>
.song-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.batch-actions {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.selected-count {
  margin-left: 15px;
  color: #666;
  font-size: 14px;
}

.avatar-uploader {
  margin-top: 10px;
}
</style>